package com.shop.jpa.impl;

import com.shop.jpa.BaseDao;
import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.transaction.Transactional;
import java.io.Serializable;

public class BaseDaoImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements BaseDao<T, ID> {

    private final Class<T> dc;

    private final EntityManager em;

	public BaseDaoImpl(JpaEntityInformation<T, ?> entityInformation, EntityManager em) {
		super(entityInformation, em);
        this.dc = null;
		this.em = em;
    }

	public BaseDaoImpl(Class<T> domainClass, EntityManager em) {
		super(domainClass, em);
        this.dc = domainClass;
		this.em = em;
	}

	@Override
	public T findSingle(ID id) {
		return this.findById(id).orElse(null);
	}

	@Transactional
	@Override
	public int recover(ID id) {
		Query query = em.createQuery("update " + dc.getSimpleName() + " set isDeleted = 0 where id = ?1");
		query.setParameter(1, id);
		return query.executeUpdate();
	}

	@Transactional
	@Override
	public int recover(Iterable<ID> ids) {
		Query query = em.createQuery("update " + dc.getSimpleName() + " set isDeleted = 0 where id in (?1)");
		query.setParameter(1, ids);
		return query.executeUpdate();
	}

	@Override
	public int remove(ID id) {
		Query query = em.createQuery("delete " + dc.getSimpleName() + " where id = ?1");
		query.setParameter(1, id);
		return query.executeUpdate();
	}

	@Override
	public int remove(Iterable<ID> ids) {
		Query query = em.createQuery("delete " + dc.getSimpleName() + " where id in (?1)");
		query.setParameter(1, ids);
		return query.executeUpdate();
	}

}
